import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ceramics/model/ab_comment.dart';
import 'package:ceramics/model/ab_oauth.dart';
import 'package:ceramics/model/ab_video.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/main/home/ab_home_page.dart';
import 'package:ceramics/pages/main/hot/ab_hot_page.dart';
import 'package:ceramics/pages/main/video/ab_video_home_page.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_oss_fetch_util.dart';
import 'package:ceramics/widgets/ab_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

import '../model/ab_singleton.dart';

late Database abDB;

initDB() async {

  var path = await getDatabasesPath();
  // if (kDebugMode) {
  //   path = "/Users/zero/Desktop";
  // }
  String dbPath = "$path/ab_ceramics.db";
  if (!File(dbPath).existsSync()) {
    var data = await rootBundle.load('js/ab_ceramics.db');
    File("$path/ab_ceramics.db").writeAsBytesSync(data.buffer.asUint8List());
  }


  abDB = await openDatabase(dbPath, version: 2, onCreate: (Database db, int version) async {
    // await db.execute(ABWorks.createTableSQL());
  },onUpgrade: (Database db, int oldVersion, int newVersion) async {
    // if (oldVersion == 1) {
    //   await db.execute("ALTER TABLE works ADD COLUMN nickname TEXT");
    //   await db.execute("ALTER TABLE works ADD COLUMN avatar TEXT");
    // }
  });

  var usersStr = await rootBundle.loadString('js/users.json');
  var usersJSON = jsonDecode(usersStr) as List<dynamic>;
  ABSingleton().users = usersJSON.map((e) => ABUser.fromJson(e)).toList();

  // await ABVideo.queryVideos();
  await OssCaches.initLocalCaches();
  await ImageCache.initLocalCache();
  // await api.allUsers();
}

Future<void> replaceUser() async {
  var sp = await SharedPreferences.getInstance();
  var didReplaced = sp.getBool('didReplaced') ?? false;
  if (!didReplaced) {
    var allRemoteUsers = await api.allUsers();
    await ABWorks.replaceUsers(allRemoteUsers);
    await ABVideo.replaceUsers(allRemoteUsers);
    await ABComment.replaceUsers(allRemoteUsers);
    sp.setBool('didReplaced', true);
  }
}

Future<void> replaceTableUser() async {
  // 将comments videos works 中的数据 where userId = ABSingleton.user 的 nickname、avatar 更新成最新的
  await abDB.update('comments', {'nickname': ABSingleton.user?.nickname, 'avatar': ABSingleton.user?.avatar}, where: 'userId = ?', whereArgs: [ABSingleton.user?.userId]);
  await abDB.update('videos', {'nickname': ABSingleton.user?.nickname, 'avatar': ABSingleton.user?.avatar}, where: 'userId = ?', whereArgs: [ABSingleton.user?.userId]);
  await abDB.update('works', {'nickname': ABSingleton.user?.nickname, 'avatar': ABSingleton.user?.avatar}, where: 'userId = ?', whereArgs: [ABSingleton.user?.userId]);

  Get.find<ABHomeController>().loadData();
  Get.find<ABHotController>().loadData();
  Get.find<ABVideoHomePageController>().initAllVideos();
}